package com.longrise.android.byjk.plugins.hra.hratabfirst;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.event.HraPaymentEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.hra.TimeUtil;
import com.longrise.android.byjk.plugins.hra.hratabsecond.MineAppointDetailActivity;
import com.longrise.android.byjk.plugins.hra.hratabthird.ChangeHraPointActivity;
import com.longrise.android.byjk.plugins.hra.hratabthird.EndorseRefreshEvent;
import com.longrise.android.byjk.plugins.hra.hratabthird.HraCheckerBean;
import com.longrise.android.byjk.plugins.hra.pay.HraPaymentActivity;
import com.longrise.android.byjk.utils.CheckCard;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.android.byjk.utils.PhoneUtils;
import com.longrise.common.base.BaseActivity2;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.PrintLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;

/**
 * Created by Administrator on 2018/1/8.
 * Hra预约检测
 */

public class HraOrderCheckActivity extends BaseActivity2<HraOrderCheckPresenter> implements HraOrderCheckContract.View, View.OnClickListener, TextWatcher {

    public static final String TAG = "HraOrderCheckActivity";
    public static final String HRAORDERCHECK = "hraordercheck";
    public static final String CHECKERBEAN = "checkerbean";
    private TextView mOrderPrice;
    private TextView mOrderType;
    private TextView mOrderDate;
    private TextView mOrderTime;
    private TextView mOrderCheckName;
    private TextView mOrderCheckSex;
    private TextView mOrderCheckCard;
    private TextView mOrderCheckPhone;
    private RelativeLayout rl_order_check_name;
    private RelativeLayout rl_order_check_sex;
    private RelativeLayout rl_order_check_cardnum;
    private RelativeLayout rl_order_check_phonenum;
    private String mOrderSex;
    private Dialog mOrderSexDialog;
    private EditText et_dialog_info;
    private TextView tv_confirm;
    private String dialogType = "";
    private String nameType = "1";
    private String cardType = "2";
    private String telType = "3";
    private Dialog mOrderInfoDialog;
    private String tv_order_name;
    private String tv_order_sex;
    private String tv_order_card;
    private String tv_order_tel;
    private Button btn_commit;
    private ImageView iv_back;
    private HraServiceBean mServiceBean;
    private TextView mStoreName;
    private TextView mStoreAdd;
    private TextView mStoreTel;
    private TextView mPrice;
    private String sexType = "";
    private Button btn_endorse_confirm;
    private RelativeLayout rl_order_commit;
    private int flags;
    private String endorse;
    private String endorseId;
    private String timeId;
    private String orderTime;
    private String bespeakdate;
    private String dateOfZh;
    private String orderId;
    private String urseName;
    private String sex;
    private String cardNum;
    private String phoneNum;
    private boolean isChangeStore;
    private HraCheckerBean mCheckerBean;


    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_hra_order_check;
    }

    @Override
    public void initView() {
        mStoreName = (TextView) findViewById(R.id.tv_order_check_name);
        mStoreAdd = (TextView) findViewById(R.id.tv_order_check_add);
        mStoreTel = (TextView) findViewById(R.id.tv_order_check_tel);
        mOrderPrice = (TextView) findViewById(R.id.tv_hra_order_price);
        mOrderType = (TextView) findViewById(R.id.tv_hra_order_type);
        mOrderDate = (TextView) findViewById(R.id.tv_order_check_date);
        mOrderTime = (TextView) findViewById(R.id.tv_order_check_time);
        mPrice = (TextView) findViewById(R.id.tv_order_price);
        mOrderCheckName = (TextView) findViewById(R.id.tv_order_name);
        mOrderCheckSex = (TextView) findViewById(R.id.tv_order_sex);
        mOrderCheckCard = (TextView) findViewById(R.id.tv_order_cardNum);
        mOrderCheckPhone = (TextView) findViewById(R.id.tv_order_phoneNum);
        rl_order_check_name = (RelativeLayout) findViewById(R.id.rl_order_check_name);
        rl_order_check_sex = (RelativeLayout) findViewById(R.id.rl_order_check_sex);
        rl_order_check_cardnum = (RelativeLayout) findViewById(R.id.rl_order_check_cardnum);
        rl_order_check_phonenum = (RelativeLayout) findViewById(R.id.rl_order_check_phonenum);
        btn_commit = (Button) findViewById(R.id.btn_hra_order_commit);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        btn_endorse_confirm = (Button) findViewById(R.id.btn_endorse_confirm);
        rl_order_commit = (RelativeLayout) findViewById(R.id.rl_order_commit);
        EventBus.getDefault().register(this);
        setToolbarVisible(false);
        getExtraData();
        initData();
        initEvent();
        setData2View();
    }

    @Override
    public void onToolbarBackClick() {

    }

    @Override
    public void setStatusBarColor() {
        super.setStatusBarColor();
        AppUtil.setStatusBarColor(this, Color.parseColor("#FF1686CC"));
    }

    public void initData() {
        boolean b = checkInfoText();
        if (b) {
            btn_commit.setEnabled(true);
            btn_commit.setBackgroundColor(Color.parseColor("#FFFBA140"));
            btn_endorse_confirm.setEnabled(true);
        } else {
            btn_commit.setEnabled(false);
            btn_commit.setBackgroundColor(Color.parseColor("#FFD8D8D8"));
            btn_endorse_confirm.setEnabled(false);
        }
    }

    public void getExtraData() {
        Intent intent = getIntent();
        mServiceBean = (HraServiceBean) intent.getSerializableExtra(HRAORDERCHECK);
        mCheckerBean = (HraCheckerBean) intent.getSerializableExtra(CHECKERBEAN);
        flags = intent.getFlags();
        switch (flags) {
            //显示提交订单
            case HraOrderFragment.HRAORDERFRAGMENT:
                rl_order_commit.setVisibility(View.VISIBLE);
                btn_endorse_confirm.setVisibility(View.GONE);
                break;
            //显示确认修改
            case ChangeHraPointActivity.CHANGEHRAPOINT:
                rl_order_commit.setVisibility(View.GONE);
                btn_endorse_confirm.setVisibility(View.VISIBLE);
                btn_endorse_confirm.setEnabled(false);
                break;
        }
    }

    public void initEvent() {
        rl_order_check_name.setOnClickListener(this);
        rl_order_check_sex.setOnClickListener(this);
        rl_order_check_cardnum.setOnClickListener(this);
        rl_order_check_phonenum.setOnClickListener(this);
        btn_commit.setOnClickListener(this);
        mOrderCheckName.addTextChangedListener(this);
        mOrderCheckCard.addTextChangedListener(this);
        mOrderCheckPhone.addTextChangedListener(this);
        mOrderCheckSex.addTextChangedListener(this);
        iv_back.setOnClickListener(this);
        btn_endorse_confirm.setOnClickListener(this);
    }

    //设置数据
    public void setData2View() {

        switch (flags) {
            //显示提交订单
            case HraOrderFragment.HRAORDERFRAGMENT:

                break;
            //显示确认修改
            case ChangeHraPointActivity.CHANGEHRAPOINT:
                String urseName = mCheckerBean.getUrseName();
                String sex = mCheckerBean.getSex();
                String cardNum = mCheckerBean.getCardNum();
                String phoneNum = mCheckerBean.getPhoneNum();
                mOrderCheckName.setText(urseName);
                mOrderCheckSex.setText(sex);
                mOrderCheckCard.setText(cardNum);
                mOrderCheckPhone.setText(phoneNum);
                break;
        }

        PrintLog.e(TAG,"urseName=:"+Control.getOrderCheckName());

        String storeName = mServiceBean.getStoreName();
        String storeAdd = mServiceBean.getStoreAdd();
        String storeTel = mServiceBean.getStorephone();
        String price = mServiceBean.getPrice();
        String machineType = mServiceBean.getMachineType();
        orderTime = mServiceBean.getOrderTime();
        bespeakdate = mServiceBean.getBespeakdate();
        String timeslot = mServiceBean.getTimeslot();

        try {
            dateOfZh = TimeUtil.getDateOfMonth(bespeakdate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        mStoreName.setText(storeName);
        mStoreAdd.setText(storeAdd);
        mStoreTel.setText(storeTel);
        mOrderPrice.setText("¥" + price);
        mOrderType.setText("HRA " + machineType);
        mOrderDate.setText(dateOfZh);
        mOrderTime.setText(timeslot);
        mPrice.setText("¥" + price);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_order_check_name:
                dialogType = nameType;
                showOrderInfoDialog(dialogType);
                break;
            case R.id.rl_order_check_sex:
                showSexDialog();
                break;
            case R.id.rl_order_check_cardnum:
                dialogType = cardType;
                showOrderInfoDialog(dialogType);
                break;
            case R.id.rl_order_check_phonenum:
                dialogType = telType;
                showOrderInfoDialog(dialogType);
                break;
            //提交订单
            case R.id.btn_hra_order_commit:
                uploadOrderInfo();
                break;
            case R.id.iv_back:
                finish();
                break;
            //确认修改
            case R.id.btn_endorse_confirm:
                uploadEndorseInfo();
                break;
        }
    }

    //点击提交订单
    public void uploadOrderInfo() {

        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("paycardno", UserInfor.getInstance().getUsersfzh());
        bean.set("payname", UserInfor.getInstance().getPersonname());
        bean.set("cardno", tv_order_card);
        bean.set("username", tv_order_name);
        bean.set("usermobile", tv_order_tel);
        bean.set("sex", changeSex(tv_order_sex));
        bean.set("storeid", mServiceBean.getStoreid());
        bean.set("machineid", mServiceBean.getMachineId());
        bean.set("timeid", mServiceBean.getTimeslotid());
        mPresenter.uploadOrderCheck(bean);
    }

    public void uploadEndorseInfo() {

        EntityBean bean = new EntityBean();
        EntityBean customerbean = new EntityBean();
        customerbean.set("storeid", mServiceBean.getStoreid());
        customerbean.set("machineid", mServiceBean.getMachineId());
        customerbean.set("timeid", mServiceBean.getTimeslotid());
        customerbean.set("areaid", mServiceBean.getAreaId());
        customerbean.set("endorse", endorse);
        customerbean.set("usermobile", tv_order_tel);
        customerbean.set("sex", changeSex(tv_order_sex));
        customerbean.set("address", mServiceBean.getStoreAdd());
        customerbean.set("storename", mServiceBean.getStoreName());
        customerbean.set("machinemodel", mServiceBean.getMachinemodel());
        customerbean.set("username", tv_order_name);
        customerbean.set("cardno", tv_order_card);
        customerbean.set("examinedate", mServiceBean.getBespeakdate());
        customerbean.set("timeslot", mServiceBean.getTimeslot());

        bean.set("oldcustomerid", endorseId);
        bean.set("oldtimeid", timeId);
        bean.set("customerbean", customerbean);
        mPresenter.uploadEndorseInfo(bean);
    }

    public String changeSex(String sex) {
        if ("男".equals(sex)) {
            sexType = "0";
        } else if ("女".equals(sex)) {
            sexType = "1";
        }
        return sexType;
    }

    //弹出填写姓名,身份证,手机号码的dialog
    public void showOrderInfoDialog(final String type) {
        final View mEditDialog = View.inflate(mContext, R.layout.dialog_invoice_edit, null);
        final TextView tv_dialog_title = (TextView) mEditDialog.findViewById(R.id.tv_dialog_title);
        final TextView tv_dialog_notice = (TextView) mEditDialog.findViewById(R.id.tv_dialog_notice);
        et_dialog_info = (EditText) mEditDialog.findViewById(R.id.et_dialog_info);
        TextView tv_cancel = (TextView) mEditDialog.findViewById(R.id.tv_cancel);
        tv_confirm = (TextView) mEditDialog.findViewById(R.id.tv_confirm);
        final LinearLayout ll_recipient_content = (LinearLayout) mEditDialog.findViewById(R.id.ll_recipient_content);
        final LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) ll_recipient_content.getLayoutParams();

        //姓名
        if (type == nameType) {
            layoutParams.height = AppUtil.dip2px(124);
            ll_recipient_content.setLayoutParams(layoutParams);
            tv_dialog_title.setText(AppUtil.getString(R.string.test_name));
            tv_dialog_notice.setVisibility(View.GONE);
            mOrderInfoDialog = DialogUtil.getInstance().creatAlertDialog(mContext, mEditDialog, 311, 169);

            et_dialog_info.setFilters(new InputFilter[]{
                    new InputFilter() {
                        @Override
                        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                                   int dstart, int dend) {

                            if (source.toString().matches("[\u4e00-\u9fa5]+")) {
                                tv_confirm.setTextColor(Color.parseColor("#FF007AFF"));
                                return source;
                            }
                            return "";
                        }
                    }
            });

//            String orderName = Control.getOrderCheckName();
            if (!TextUtils.isEmpty(tv_order_name)) {
                et_dialog_info.setText(tv_order_name);
                et_dialog_info.setSelection(tv_order_name.length());
            }
        } else if (type == cardType) {    //身份证
            layoutParams.height = AppUtil.dip2px(124);
            ll_recipient_content.setLayoutParams(layoutParams);
            tv_dialog_title.setText(AppUtil.getString(R.string.test_card));
            tv_dialog_notice.setVisibility(View.GONE);
            mOrderInfoDialog = DialogUtil.getInstance().creatAlertDialog(mContext, mEditDialog, 311, 169);
//            String orderCardNum = Control.getOrderCheckCard();
            if (!TextUtils.isEmpty(tv_order_card)) {
                et_dialog_info.setText(tv_order_card);
                et_dialog_info.setSelection(tv_order_card.length());
            }
        } else if (type == telType) {    //手机号码
            layoutParams.height = AppUtil.dip2px(124);
            ll_recipient_content.setLayoutParams(layoutParams);
            tv_dialog_title.setText(AppUtil.getString(R.string.test_tel));
            tv_dialog_notice.setVisibility(View.GONE);
            mOrderInfoDialog = DialogUtil.getInstance().creatAlertDialog(mContext, mEditDialog, 311, 169);
            et_dialog_info.setInputType(InputType.TYPE_CLASS_NUMBER);
//            String orderPhone = Control.getOrderCheckPhone();
            if (!TextUtils.isEmpty(tv_order_tel)) {
                et_dialog_info.setText(tv_order_tel);
                et_dialog_info.setSelection(tv_order_tel.length());
            }
        }

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dismiss();
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String dialigInfo = et_dialog_info.getText().toString();
                if (!TextUtils.isEmpty(dialigInfo)) {
                    if (type == nameType) {
                        mOrderCheckName.setText(dialigInfo);
//                        Control.setOrderCheckName(dialigInfo);
                        DialogUtil.getInstance().dismiss();
                    } else if (type == cardType) {
                        try {
                            if (CheckCard.IDCardValidate(dialigInfo)) {
                                mOrderCheckCard.setText(dialigInfo);
//                                Control.setOrderCheckCard(dialigInfo);
                                DialogUtil.getInstance().dismiss();
                            } else {
                                showToast(getString(R.string.cardno_type_error));
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                    } else if (type == telType) {
                        if (PhoneUtils.isPhoneNumber(et_dialog_info.getText().toString())) {
                            mOrderCheckPhone.setText(dialigInfo);
//                            Control.setOrderCheckPhone(dialigInfo);
                            DialogUtil.getInstance().dismiss();
                        } else {
                            showToast(getString(R.string.tel_hint));
                        }
                    }
                }
            }
        });

        et_dialog_info.addTextChangedListener(this);
        mOrderInfoDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        mOrderInfoDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    //弹出选择性别的dialog
    public void showSexDialog() {
        View mContentDialog = View.inflate(mContext, R.layout.dialog_sex_select, null);
        final RadioButton rb_sex_male = (RadioButton) mContentDialog.findViewById(R.id.rb_sex_male);
        final RadioButton rb_sex_female = (RadioButton) mContentDialog.findViewById(R.id.rb_sex_female);
        RelativeLayout rl_content_item1 = (RelativeLayout) mContentDialog.findViewById(R.id.rl_sex_item1);
        RelativeLayout rl_content_item2 = (RelativeLayout) mContentDialog.findViewById(R.id.rl_sex_item2);
//        String orderSex = Control.getOrderCheckSex();
        if (!TextUtils.isEmpty(tv_order_sex)) {
            if (tv_order_sex.equals(AppUtil.getString(R.string.order_sex_male))) {
                rb_sex_male.setChecked(true);
            } else if (tv_order_sex.equals(AppUtil.getString(R.string.order_sex_female))) {
                rb_sex_female.setChecked(true);
            }
        }

        rl_content_item1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rb_sex_male.setChecked(true);
            }
        });

        rl_content_item2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rb_sex_female.setChecked(true);
            }
        });


        mOrderSexDialog = DialogUtil.getInstance().creatAlertDialog(mContext, mContentDialog, 311, 183);
        mOrderSexDialog.setCanceledOnTouchOutside(true);
        rb_sex_male.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                DialogUtil.getInstance().dismiss();
                mOrderCheckSex.setText(AppUtil.getString(R.string.order_sex_male));
//                Control.setOrderCheckSex(AppUtil.getString(R.string.order_sex_male));
            }
        });

        rb_sex_female.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                DialogUtil.getInstance().dismiss();
                mOrderCheckSex.setText(AppUtil.getString(R.string.order_sex_female));
//                Control.setOrderCheckSex(AppUtil.getString(R.string.order_sex_female));
            }
        });

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        boolean b = checkInfoText();
        if (b) {
            btn_commit.setEnabled(true);
            btn_commit.setBackgroundColor(Color.parseColor("#FFFBA140"));
            btn_endorse_confirm.setEnabled(true);
        } else {
            btn_commit.setEnabled(false);
            btn_commit.setBackgroundColor(Color.parseColor("#FFD8D8D8"));
            btn_endorse_confirm.setEnabled(false);
        }

        if (dialogType == nameType || dialogType == telType || dialogType == cardType) {
            if(TextUtils.isEmpty(s)){
                tv_confirm.setTextColor(Color.parseColor("#FF818181"));
            }else {
                tv_confirm.setTextColor(Color.parseColor("#FF007AFF"));
            }
        }
    }

    //检查信息是否填写
    public boolean checkInfoText() {
        tv_order_name = mOrderCheckName.getText().toString();
        tv_order_sex = mOrderCheckSex.getText().toString();
        tv_order_card = mOrderCheckCard.getText().toString();
        tv_order_tel = mOrderCheckPhone.getText().toString();
        if (TextUtils.isEmpty(tv_order_name)) {
            return false;
        }

        if (TextUtils.isEmpty(tv_order_sex)) {
            return false;
        }
        if (TextUtils.isEmpty(tv_order_card)) {
            return false;
        }

        if (TextUtils.isEmpty(tv_order_tel)) {
            return false;
        }
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void registerOrderEvent(HraOrderEvent event) {
        endorse = event.getEndorse();
        endorseId = event.getEndorseId();
        timeId = event.getTimeId();
        orderId = event.getOrderid();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerHraPaymentEvent(HraPaymentEvent event){
         if(event.isClose()){
             finish();
         }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registCloseEvent(EndorseRefreshEvent event){
        if(event.isClose()){ //关闭界面
            finish();
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 去支付页面支付
     */
    @Override
    public void toPay(String orderid, String name, String cardno, String number, String price) {
        HraPaymentActivity.toPushActivity(this, orderid, name, cardno, number, price);
    }

    //跳转到预约详情界面
    @Override
    public void start2DetailActivity() {
        EndorseRefreshEvent event = new EndorseRefreshEvent();
        event.setClose(true);
        Intent intent = new Intent(this, MineAppointDetailActivity.class);
        intent.putExtra(MineAppointDetailActivity.MINEORDERID,orderId);
        intent.putExtra(MineAppointDetailActivity.HRASERVICEBACK,true);
        startActivity(intent);
    }

    @Override
    public void setBtnEnable(boolean isable) {
        btn_endorse_confirm.setEnabled(isable);
    }
}
